<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>WebSocket</title>
	<script src="socket.io/socket.io.js"></script>
	<script>
	
		var socket;
		function btnConnect(){
			if(socket===undefined){
				socket=io('http://{{ ip }}:{{ port }}');
			}
		socket.on('connect',function(){
			console.log('client connect');
		});
		socket.on('connecting',function(){
			console.log('connecting');
		});
		socket.on('disconnect',function(){
			console.log('disconnect');
		});
		socket.on('connect_failed',function(){
			console.log('connect_failed');
		});

		socket.on('news',function(recv){
			console.log('from server : '+recv.msg);
			socket.emit('sendMyData',{msg:'msg received'});
		});
		socket.on('system',function(data){
			var sect_ul=document.querySelector('#showMsg ul');
			var ttime=new Date(data.time);
			var ddate=ttime.getHours()+':'+ttime.getMinutes()+':'+ttime.getSeconds();
			sect_ul.innerHTML+='<li>'+data.author+': '+data.type+' '+data.text+' '+ddate+'</li>';	


		});
		socket.on('message',function(data){
			var sect_ul=document.querySelector('#showMsg ul');
			var ttime=new Date(data.time);
			var ddate=ttime.getHours()+':'+ttime.getMinutes()+':'+ttime.getSeconds();
			sect_ul.innerHTML+='<li>'+data.author+': '+data.text+' '+ddate+'</li>';	

		});
		socket.on('private message',function(data){
			var sect_ul=document.querySelector('#showMsg ul');
			var ttime=new Date(data.time);
			var ddate=ttime.getHours()+':'+ttime.getMinutes()+':'+ttime.getSeconds();
			sect_ul.innerHTML+='<li>'+data.author+'->'+data.to+': '+data.text+' '+ddate+'</li>';	


		});
	}
		function ws_send(){
			var txt=document.querySelector("#text").value;
			//ws.send(txt);
			var cname=document.querySelector('#cname');
			if(cname.value!=''){
				socket.emit('private message',cname.value,txt);	
			}else{
				socket.send(txt);
			}
			//socket.emit('sendMyData',{msg:txt});
			document.querySelector("#text").value="";
		}
	</script>
</head>
<body>
	<button onclick="btnConnect();">connect</button>
	<section id='showMsg' style="display:block;margin-bottom:30px;height:100px;overflow-y:auto;border:1px solid gray;">
		<ul></ul>	
	</section>
	<input type='text' id='cname' placeholder='client name' />
	<textarea id="text" rows="3" cols="50"></textarea>
	<section>
		<button onclick="ws_send();">send</button>
	</section>
</body>
</html>
